
function calculateKD({ data = [], n = 21, m1 = 3, m2 = 3 }) {
    let result = {}
    let len = data.length
    let rsv = [] // RSV数组
    let k = [] // K值数组
    let d = [] // D值数组

    // 计算RSV
    for (let i = 0; i < len; i++) {
        if (i == 0) {
            rsv.push(0)
        } else {
            let high = Math.max(...data.slice(i - n + 1, i + 1).map(x => x.high))
            let low = Math.min(...data.slice(i - n + 1, i + 1).map(x => x.low))
            let c = data[i].close
            rsv.push((c - low) / (high - low) * 100)
        }
    }

    // 计算K值
    for (let i = 0; i < len; i++) {
        if (i < m1 - 1) {
            k.push(0)
        } else {
            let sum = rsv.slice(i - m1 + 1, i + 1).reduce((a, b) => a + b, 0)
            k.push(Number((sum / m1).toFixed(2)))
        }
    }

    // 计算D值
    for (let i = 0; i < len; i++) {
        if (i < m2 - 1) {
            d.push(0)
        } else {
            let sum = k.slice(i - m2 + 1, i + 1).reduce((a, b) => a + b, 0)
            d.push(Number((sum / m2).toFixed(2)))
        }
    }

    // 计算J值
    /*
    for (let i = 0; i < len; i++) {
        if (i < m2 - 1) {
            j.push(0)
        } else {
            let sum = d.slice(i - m2 + 1, i + 1).reduce((a, b) => a + b, 0)
            j.push(Number((sum / m2).toFixed(2)))
        }
    }
    */

    // rsv: rsv[index],
    result = { k, d }

    return result
}

// 使用示例
/*
const data = [
    { high: 10, low: 5, close: 8 },
    { high: 12, low: 6, close: 9 },
    { high: 15, low: 7, close: 11 },
    // ... 更多数据
];
*/

module.exports = calculateKD

